package com.lijian.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.lijian.base.Result;
import com.lijian.mapper.PermissionMapper;
import com.lijian.model.SysPermission;
import com.lijian.service.PermissionService;
import com.lijian.util.TreeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public Result<JSONArray> listAllPermission() {
        List datas = permissionMapper.findAll();
        JSONArray array = new JSONArray();
        TreeUtils.setPermissionsTree(0, datas, array);
        return Result.success(array);
    }

    @Override
    public Result<SysPermission> listByRoleId(Integer roleId) {
        List<SysPermission> datas = permissionMapper.listByRoleId(roleId);
        return Result.success(0, datas);
    }

    @Override
    public Result<SysPermission> findMenuAll() {
        return Result.success(0, permissionMapper.findAll());
    }

    @Override
    public Result<SysPermission> save(SysPermission sysPermission) {
        return (permissionMapper.save(sysPermission) > 0) ? Result.success() : Result.error();
    }

    @Override
    public SysPermission findSysPermissionById(Integer id) {
        return permissionMapper.findSysPermissionById(id);
    }

    @Override
    public Result update(SysPermission sysPermission) {
        return (permissionMapper.update(sysPermission) > 0) ? Result.success() : Result.error();
    }

    @Transactional
    @Override
    public Result delete(Integer id) {
        permissionMapper.deleteById(id);
        //删除对应的父节点
        permissionMapper.deleteByParentId(id);
        return Result.success();
    }

    @Override
    public Result findMenu(Integer userId) {
        List<SysPermission> datas = permissionMapper.findListByUserId(userId);
        //获取所有type=1的菜单
        datas = datas.stream().filter(p -> p.getType().equals(1)).collect(Collectors.toList());
        JSONArray array = new JSONArray();
        TreeUtils.setPermissionsTree(0, datas, array);
        return Result.success(array);
    }
}
